// packageA/pages/returnPartsAdd/returnPartsAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //提交按钮禁用
    disabled:false,
    //传参来的id
    id:null,
    //是否是修改
    isEdit:false,
    //修改信息回显
    editInfo:{
      returnAddress:true
    },
    //避免表单重复提交
    code:null,
    //数量
    partNum:1,
    //返还地
    returnAddressList: [
      { text: '厂家', value: true },
      { text: '仓库', value: false }
    ],
    returnAddressWord: '厂家',
    //厂家/仓库选择框
    showDepart:false,
    //厂家/仓库选择数据
    departList:[],
    //搜索厂家/仓库
    valueSearchDepart:'',
    //物流公司选择框
    showLogistics:false,
    //物流公司选择数据
    logisticsList:[],
    //上传的图片
    imgUrls:[],
    //服务详情
    serviceDetails:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      code:Base64.encode(new Date() + app.globalData.userInfo.userName)
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('旧件返还传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id,
          isEdit:true
        })
        //获取要修改的数据
        this.getInfo();  
      }

      if(paramObj.afterssrid){
        this.setData({
          afterssrid: paramObj.afterssrid
        })
        //获取售后服务详情
        this.getAfterDetail();
      }
    }
  },

  //提交表单
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo;  

    let partName=obj.partName.trim();
    let logOddNum=obj.logOddNum.trim();
    let freight=obj.freight.trim();

    //表单验证
    if(!this.formNotEmpty(partName,'partNameMessage','请输入配件名称')){
      return;
    } 

    if(!editInfo.returnDepart){
      Toast.fail('请选择厂家/仓库');
      return;
    }

    if(!editInfo.logistics){
      Toast.fail('请选择物流');
      return;
    }

    if(!this.formNotEmpty(logOddNum,'logOddNumMessage','请输入物流单号')){
      return;
    }
    
    if(freight!='' && freight!=null){
      if(!this.formNumber(freight,'freightMessage','费用为数字')){
        return;
      }
    }

    let param={
      className:'afterSaleReturnParts',
      data:{
        requestToken: td.code,
        id: td.id,
        afterssrid: td.afterssrid,
        partName: partName,
        partNum: td.partNum,
        returnAddress: editInfo.returnAddress,
        returnDepart: editInfo.returnDepart,
        returnDepartName: editInfo.returnDepartName,
        logistics: editInfo.logistics,
        logOddNum: logOddNum,
        freight: Number(freight),
        remark: obj.remark,
        pic: td.imgUrls
      }
    }

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    //console.log(param);

    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');  

        //售后记录增加详情
        this.insertAfterDetail();

        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })  
  },

  //获取要修改的数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'afterSaleReturnParts',
      data: {
        id:this.data.id,
        selectFields: ['id','afterssrid','returnAddress','partName','returnDepart','returnDepartName','logistics','remark','logOddNum','confirm','partNum','freight','pic']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;

        if(result[0].freight){
          result[0].freight=result[0].freight.toFixed(2);
        }

        console.log('旧件返还信息回显');
        console.log(result[0]);

        this.setData({
          editInfo: result[0]
        })
      }
    }).catch((error) => {
    })
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //选择返还地
  onChangeReturnAddress({detail}){
    let str='';
    if(detail){
      str='厂家';
    }else{
      str='仓库';
    }

    let returnAddress='editInfo.returnAddress';
    this.setData({
      [returnAddress]: detail,
      returnAddressWord: str
    })
  },

  //显示厂家/仓库选择框
  onShowDepart(){
    this.setData({
			showDepart: true
    })
    this.getDepartList();
  },

  //查询厂家/仓库
  getDepartList(){
    this.setData({
      departList: []
    })

    let param = {
      isAuth: false,
      data: {
        searchAll: true,  
        selectFields: ['id', 'name']
      }
    }

    //查询厂家/仓库
    if(this.data.editInfo.returnAddress){
      param.className='depart';
      param.data.type=2;
    }else{
      param.className='partsDepots';
    }

    //模糊查询
    if(this.data.valueSearchDepart){
      param.data.name='%' + this.data.valueSearchDepart + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });
        this.setData({
          departList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏厂家/仓库选择框
  onCloseDepart(){
    this.setData({
      showDepart: false,
      valueSearchDepart:''
    })
  },

  //确认厂家/仓库
  onConfirmDepart(e){
    let returnDepart='editInfo.returnDepart';
    let returnDepartName='editInfo.returnDepartName';
    this.setData({
      [returnDepart]:e.detail.value.id,
      [returnDepartName]:e.detail.value.text,
      disabled:false
    })
    this.onCloseDepart();
  },

  //搜索厂家/仓库
  onChangeDepartVal(e){
    this.setData({
      valueSearchDepart: e.detail
    })
    this.getDepartList();
  },

  //显示物流公司选择框
  onShowLogistics(){
    this.setData({
      showLogistics: true
    })
    this.getLogisticsList();
  },

  //查询物流公司
  getLogisticsList(){
    let param = {
      isAuth: false,
      className: 'logisticsCompany',
      data: {
        searchAll: true,
        selectFields: ['id', 'name']
      }
    }
    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });
        this.setData({
          logisticsList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏物流公司选择框
  onCloseLogistics(){
    this.setData({
			showLogistics: false
    })
  },

  //确认物流公司
  onConfirmLogistics(e){
    let logistics='editInfo.logistics';
    this.setData({
      [logistics]: e.detail.value.text,
      disabled: false
    })
    this.onCloseLogistics();
  },

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgUrls=data.detail;

    if(imgUrls.length){
      this.setData({
        imgUrls: imgUrls
      })
    }
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //数字验证
  formNumber(field,messageField,messageCon){
    if(!(/^\d+(\.\d+)?$/.test(field))){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }  
  },

  //获取输入的数量
  onChangePartNum(event) {  
    this.setData({
      partNum: event.detail
    })
  },

  //获取售后服务详情
  getAfterDetail(){
    let param = {
      isAuth: false,
      className: 'afterSaleServiceRecord',
      data: {
        id:this.data.afterssrid,
        selectFields: ['id','serviceDetails']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        this.setData({
          serviceDetails: result[0].serviceDetails
        })
      }
    }).catch((error) => {
    })
  },

  //售后记录增加详情，增加旧件返还标识
  insertAfterDetail(){
    let td=this.data;
    let user = app.globalData.userInfo;
    let serviceDetails=td.serviceDetails;

    if(td.isEdit){
      serviceDetails.push({
        content: user.userName + "修改旧件返还信息",
        datetime: util.timeFormat(new Date())
      });
    }else{
      serviceDetails.push({
        content: user.userName + "添加旧件返还信息",
        datetime: util.timeFormat(new Date())
      });
    }

    let param={
      className:'afterSaleServiceRecord',
      data:{
        id:td.afterssrid,
        serviceDetails:serviceDetails,
        oldStore: true
      }
    }

    CommonService.goSave(param).then(res=>{
    }).catch((error) => {
    })
  },

  //物流单号扫码
  onScanCode(e) {
    var _this = this;
    wx.scanCode({
      success: (res) => {
        let logOddNum='editInfo.logOddNum';
        _this.setData({
          [logOddNum]: res.result
        })
      }
    })
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})